package com.isc.tcpFileUpload01;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * 1.编写一个服务端和一个客户端
 * 2.服务器在8888端口监听
 * 3.客户端连接到服务器，发送一张图片 d:\\5t5.jpg
 * 4.服务器端接收到客户端发送的图片，保存到src下，发送"收到图片"再退出
 * 5.客户端接收到服务器端发送的"收到图片",再退出
 * 6.该程序要求使用StreamUtils.java
 */
public class Client {
    public static void main(String[] args) throws IOException {
        //请求的服务器ip地址
        byte[] addr = new byte[]{127, 0, 0, 1};
        //端口号
        int port = 8888;
        Socket socket = new Socket(InetAddress.getByAddress(addr), port);

        //向服务器发送图片
        //1.在磁盘上读取该图片，以字节数组的方式保存
        String filePath = "d:\\5t5.jpg";
        File file = new File(filePath);
        FileInputStream fis = new FileInputStream(file);
        byte[] buf = new byte[1024];
        int readLength = 0;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        while ((readLength = fis.read(buf)) != -1) {
            baos.write(buf, 0, readLength);//向baos流写入每次暂存的buf数据(追加方式)
        }
        //temp是文件暂存的字节数组
        byte[] temp = baos.toByteArray();
        System.out.println("客户端读取文件完成~");
        //关闭资源
        baos.close();
        fis.close();

        //2.把buf中存放的图片数据发送给服务器端
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write(temp);
        socket.shutdownOutput();//文件结束符
        System.out.println("文件发送成功...");

        //客户端接收到服务器端发送的"收到图片"
        InputStream inputStream = socket.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
        String s = br.readLine();
        System.out.println("接收到服务器端发送的消息是:" + s);

        //关闭资源
        br.close();
        outputStream.close();
        socket.close();
    }
}
